"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/5/29 10:44
@Description :

"""


# 自定义序列化方式  函数
def student_serializable(obj):
    if isinstance(obj, Student):
        return {'name': obj.name, 'age': obj.age, 'score': obj.score}
    raise TypeError('type error')


class Student:
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def __str__(self):
        return f'name = {self.name} ,age = {self.age} ,score =  {self.score}'


import json

if __name__ == '__main__':
    """
        lst = [1,2,3,45]
        lst_str = json.dumps(lst)
        print(lst_str,type(lst_str))
    """
    student = Student('tom', 20, 90)
    """
     # json不能直接格式化object类型的数据 但是可以先获取对象属性的字典形式数据 对象.__dict__
    student_dict = student.__dict__
    # 写入文本  typeError: Object of type Student is not JSON serializable
    student_str = json.dumps(student_dict, ensure_ascii=False, indent=2)
    with open('student.json', 'w') as f:
        f.write(student_str)
    """

    #  default=student_serializable  指定数据的序列化器
    json_str = json.dumps(student, ensure_ascii=False, indent=2, default=student_serializable)
    print(json_str, type(json_str))
    with open('student.json', 'w') as f:
        f.write(json_str)

